package com.news.filter;

import entity.User;
import org.springframework.stereotype.Controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@WebFilter(filterName="firstFilter", urlPatterns = {"/news/*","index.jsp"})
public class LoginFilter  implements Filter {

    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/user/login","/login.jsp","/login")));
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        String path = req.getRequestURI().substring(req.getContextPath().length()).replaceAll("[/]+$", "");
        System.out.println(path);
        boolean allowedPath = ALLOWED_PATHS.contains(path);
        if(allowedPath){
            filterChain.doFilter(req,resp);
        }else{
            if(user!=null){
                System.out.println("测试");
                filterChain.doFilter(req,resp);
            }else{
                System.out.println("测试111");
                resp.sendRedirect(req.getContextPath()+"/login.jsp");
                return ;
            }
        }

    }

    @Override
    public void destroy() {

    }
}


